package com.zegoto.design.design.struct.flyweight;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 享元对象
class Character {
    private char c;

    public Character(char c) {
        this.c = c;
    }

    public void draw(int x, int y) {
        System.out.println("Drawing character " + c + " at (" + x + ", " + y + ")");
    }
}

// 享元工厂
class CharacterFactory {
    private Map<java.lang.Character, Character> pool;

    public CharacterFactory() {
        this.pool = new HashMap<>();
    }

    public Character getCharacter(char c) {
        Character character = pool.get(c);
        if (character == null) {
            character = new Character(c);
            pool.put(c, character);
        }
        return character;
    }
}

// 非享元对象，表示文本
class Text {
    private List<Character> characters;
    private CharacterFactory factory;

    public Text(CharacterFactory factory) {
        this.characters = new ArrayList<>();
        this.factory = factory;
    }

    public void addCharacter(char c, int x, int y) {
        characters.add(factory.getCharacter(c));
        characters.get(characters.size() - 1).draw(x, y);
    }
}


public class FlyweightDemo {
    // 客户端使用享元和非享元对象来编辑文本
    public static void main(String[] args) {
        CharacterFactory factory = new CharacterFactory();
        Text text = new Text(factory);
        text.addCharacter('H', 0, 0);
        text.addCharacter('e', 10, 0);
        text.addCharacter('l', 20, 0);
        text.addCharacter('l', 30, 0);
        text.addCharacter('o', 40, 0);
    }
}
